package com.bytecamp.testplatform.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;

/**
 * 适配火山引擎豆包API的客户端工具类（基于你的测试代码重构）
 */
@Component  // 注入Spring容器，方便依赖注入
@Slf4j
public class AiClientUtil {

    // 从配置文件注入参数（避免硬编码）
    @Value("${doubao.api-url}")
    private String apiUrl;

    @Value("${doubao.api-key}")
    private String apiKey;

    @Value("${doubao.model}")
    private String model;

    @Value("${doubao.max-tokens}")
    private Integer maxTokens;

    private final RestTemplate restTemplate;

    // 构造函数注入RestTemplate（推荐，而非手动new）
    public AiClientUtil(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 调用豆包API生成测试用例
     * @param prompt 提示词文本
     * @return AI生成的用例内容（纯文本）
     */
    public String generateCasesByDoubao(String prompt) {
        try {
            // 1. 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            // 2. 构建请求体（严格遵循你的测试代码中的结构）
            JSONObject requestBody = new JSONObject();
            requestBody.put("model", model);
            requestBody.put("max_completion_tokens", maxTokens);

            // 构造消息体（role + content数组）
            JSONObject textContent = new JSONObject();
            textContent.put("type", "text");
            textContent.put("text", prompt);  // 传入生成用例的提示词

            JSONArray contentArray = new JSONArray();
            contentArray.add(textContent);

            JSONObject message = new JSONObject();
            message.put("role", "user");  // 必须为"user"
            message.put("content", contentArray);

            JSONArray messagesArray = new JSONArray();
            messagesArray.add(message);
            requestBody.put("messages", messagesArray);

            // 3. 发送POST请求
            HttpEntity<String> requestEntity = new HttpEntity<>(
                    JSON.toJSONString(requestBody),  // 转为JSON字符串
                    headers
            );

            log.info("调用豆包API，请求参数：{}", requestBody);
            ResponseEntity<String> response = restTemplate.exchange(
                    apiUrl,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            // 4. 解析响应（适配你的测试代码中的结构）
            if (!response.getStatusCode().is2xxSuccessful()) {
                log.error("豆包API调用失败，状态码：{}，响应：{}",
                        response.getStatusCode(), response.getBody());
                throw new RuntimeException("API返回非成功状态：" + response.getStatusCode());
            }

            String responseBody = response.getBody();
            log.info("豆包API响应：{}", responseBody);

            JSONObject responseJson = JSON.parseObject(responseBody);
            JSONArray choices = responseJson.getJSONArray("choices");
            if (choices == null || choices.isEmpty()) {
                throw new RuntimeException("API响应中无有效用例内容");
            }

            // 提取回复内容（严格按你的测试代码解析）
            JSONObject firstChoice = choices.getJSONObject(0);
            JSONObject assistantMessage = firstChoice.getJSONObject("message");
            String answer = assistantMessage.getString("content");

            if (answer == null || answer.trim().isEmpty()) {
                throw new RuntimeException("API返回空内容");
            }

            return answer;

        } catch (Exception e) {
            log.error("豆包API调用异常", e);
            throw new RuntimeException("生成测试用例失败：" + e.getMessage());
        }
    }
}